<template>
    <div class="game-container">
        <!-- 分数显示 -->
        <van-config-provider :theme-vars="themeVars">
            <div class="score">得分：{{ state.score }}</div>
            <!-- 游戏区域 -->
            <div class="game-board">
                <div v-for="(cell, index) in grid" :key="index" :class="{
                    'cell': true,
                    'snake': cell === 1,
                    'head': cell === 2,
                    'food': cell === 3
                }"></div>
            </div>
            <!-- 控制按钮 -->
            <div class="controls">
                <van-button style="width: 70%;" :type="state.isPlaying ? 'danger' : 'primary'" @click="toggleGame">
                    {{ state.isPlaying ? '暂停' : '开始' }}
                </van-button>
                <van-button style="flex: 1;" type="warning" @click="resetGame">重置</van-button>
            </div>
            <!-- 方向控制 -->
            <div class="direction-keys">
                <div class="upAndDown">
                    <van-button class="up" @touchstart="changeDirection('up')">
                        {{ '↑' }}
                    </van-button>
                    <van-button class="down" @touchstart="changeDirection('down')">
                        {{ '↓' }}
                    </van-button>
                    <van-button class="left" @touchstart="changeDirection('left')">
                        {{ '←' }}
                    </van-button>
                    <van-button class="right" @touchstart="changeDirection('right')">
                        {{ '→' }}
                    </van-button>
                </div>
            </div>
            <!-- 游戏结束弹窗 -->
            <van-dialog v-model:show="state.gameOverVisible" title="游戏结束" :showConfirmButton="false">
                <div class="dialog-content">
                    <p>最终得分：{{ state.score }}</p>
                    <van-button block type="primary" @click="resetGame">重新开始</van-button>
                </div>
            </van-dialog>
        </van-config-provider>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ConfigProvider, Dialog } from 'vant'

// 游戏配置
const GRID_SIZE = 15 // 网格大小
const INIT_SPEED = 150 // 初始速度

// 游戏状态
const state = reactive({
    snake: initSnake(),
    food: null, // 延迟初始化
    direction: 'right',
    nextDirection: 'right',
    isPlaying: false,
    score: 0,
    gameOverVisible: false
})

// 添加初始化方法
function initSnake() {
    return [
        { x: 7, y: 7 },
        { x: 6, y: 7 },
        { x: 5, y: 7 }
    ]
}

// 生成食物（排除蛇身位置）
function generateFood() {
    let newFood
    do {
        newFood = {
            x: Math.floor(Math.random() * GRID_SIZE),
            y: Math.floor(Math.random() * GRID_SIZE)
        }
    } while (state.snake.some(segment =>
        segment.x === newFood.x && segment.y === newFood.y
    ))
    return newFood
}

// 游戏网格计算
const grid = computed(() => {
    const grid = Array(GRID_SIZE * GRID_SIZE).fill(0)
    // 绘制蛇身
    state.snake.forEach((segment, index) => {
        const pos = segment.y * GRID_SIZE + segment.x
        grid[pos] = index === 0 ? 2 : 1 // 2表示头部，1表示身体
    })
    // 绘制食物
    const foodPos = state.food?.y * GRID_SIZE + state.food?.x
    grid[foodPos] = 3
    return grid
})

// 移动逻辑
function move() {
    if (!state.isPlaying) return
    const head = { ...state.snake[0] } // 修正为拷贝蛇头位置
    switch (state.nextDirection) {
        case 'up': head.y--; break
        case 'down': head.y++; break
        case 'left': head.x--; break
        case 'right': head.x++; break
    }
    // 碰撞检测
    if (head.x < 0 || head.x >= GRID_SIZE ||
        head.y < 0 || head.y >= GRID_SIZE ||
        state.snake.some(segment =>
            segment.x === head.x && segment.y === head.y
        )) {
        gameOver()
        return
    }

    state.snake.unshift(head)

    // 吃到食物
    if (head.x === state.food.x && head.y === state.food.y) {
        state.score += 10
        state.food = generateFood()
    } else {
        state.snake.pop()
    }

    state.direction = state.nextDirection
}

// 游戏控制
const gameInterval = ref(null)

function toggleGame() {
    state.isPlaying = !state.isPlaying
    if (state.isPlaying) {
        gameInterval.value = setInterval(move, INIT_SPEED)
    } else {
        clearInterval(gameInterval.value)
    }
}

function resetGame() {
    state.snake = initSnake() // 使用 initSnake 初始化蛇
    state.food = generateFood()
    state.direction = 'right'
    state.nextDirection = 'right'
    state.score = 0
    state.gameOverVisible = false
    state.isPlaying = false
}

function gameOver() {
    clearInterval(gameInterval.value)
    state.gameOverVisible = true
    state.isPlaying = false
}

function changeDirection(newDir) {
    const opposite = {
        up: 'down',
        down: 'up',
        left: 'right',
        right: 'left'
    }
    if (newDir !== opposite[state.direction]) {
        state.nextDirection = newDir
    }
}

// 主题配置
const themeVars = {
    buttonPrimaryBackground: '#07c160',
    buttonPrimaryBorderColor: '#07c160'
}

// 键盘事件监听
function handleKeydown(e) {
    const keyMap = {
        ArrowUp: 'up',
        ArrowDown: 'down',
        ArrowLeft: 'left',
        ArrowRight: 'right'
    }
    if (keyMap[e.key]) {
        e.preventDefault()
        changeDirection(keyMap[e.key])
    }
}
onMounted(() => {
    window.addEventListener('keydown', handleKeydown)
    state.food = generateFood() // 确保事件监听后再生成食物
})

onUnmounted(() => {
    window.removeEventListener('keydown', handleKeydown)
})
</script>

<style lang="scss" scoped>
.game-container {
    width: 100%;
    padding: 20px;
    max-width: 500px;
    margin: 0 auto;
}

.score {
    font-size: 20px;
    color: #333;
    margin-bottom: 15px;
    text-align: center;
    font-weight: bold;
}

.game-board {
    display: grid;
    grid-template-columns: repeat(15, 1fr);
    gap: 2px;
    background: #f8f8f8;
    border: 2px solid #eee;
    border-radius: 8px;
    padding: 2px;
    margin-bottom: 20px;
}

.cell {
    aspect-ratio: 1;
    background: white;
    border-radius: 3px;
}

.snake {
    background: #07c160;
}

.head {
    background: #059048;
}

.food {
    background: #ff4d4f;
    border-radius: 50%;
}

.controls {
    width: 100%;
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
}

.direction-keys {
    width: 100%;
    height: auto;
    min-height: 150px;
    display: flex;
    flex-direction: row;
    margin-top: 20px;
    justify-content: space-around;
    align-items: center;
    position: relative;
    .upAndDown {
        position: absolute;
        width: 150px;
        height: 150px;
        border-radius: 50%;
        background-color: #ff4d4f;
        overflow: hidden;
        .up {
            position: absolute;
            top: 5px;
            left: 50%;
            transform: translateX(-50%);
        }
        .down {
            position: absolute;
            bottom: 5px;
            left: 50%;
            transform: translateX(-50%);
        }
        .left {
            position: absolute;
            top: 50%;
            left: 5px;
            transform: translateY(-50%);
        }
        .right {
            position: absolute;
            top: 50%;
            right: 5px;
            transform: translateY(-50%);
        }
    }
}

.dialog-content {
    padding: 20px;
    text-align: center;
}

.dialog-content p {
    margin-bottom: 15px;
    font-size: 16px;
}
</style>
